package com.ali.common;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class DesUtil {
    private static final String DES = "DES";

    private static final String ALGORITHM_SHA1 = "SHA1PRNG";

    /**
     * DES加密
     */
    public static String encrypt(String content, String key) {
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);

        try {
            Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
            byte[] doFinalByte = cipher.doFinal(contentByte);
            return Base64Util.encrypt(doFinalByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Cipher
     */
    private static Cipher getCipher(String key, int opmode) {
        try {
            Cipher cipher = Cipher.getInstance(DES);
            SecretKey secretKey = getSecretKey(key);
            cipher.init(opmode, secretKey);
            return cipher;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取SecretKey
     */
    private static SecretKey getSecretKey(String key) {
        byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);

        try {
            SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_SHA1);
            secureRandom.setSeed(keyByte);
            KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
            keyGenerator.init(secureRandom);
            return keyGenerator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * DES解密
     */
    public static String decrypt(String encryptStr, String key) {
        try {
            byte[] encryptStrByte = Base64Util.getByteByDecrypt(encryptStr);

            Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
            byte[] doFinalByte = cipher.doFinal(encryptStrByte);
            return new String(doFinalByte, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}